package com.yuxue.service.impl;

import com.google.common.collect.Maps;
import com.yuxue.constant.Constant;
import com.yuxue.service.CardService;
import com.yuxue.util.FileUtil;
import com.yuxue.util.GenerateIdUtil;
import com.yuxue.util.IdCardUtil;
import com.yuxue.util.ImageUtil;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;
import java.util.Vector;

/**
 * @Description 证件识别
 * @Author yuxue
 * @Date 2024/12/20 0020 11:56
 */
@Service
public class CardServiceImpl implements CardService {

    @Override
    public Object recognise(String filePath, boolean reRecognise) {

        filePath = filePath.replaceAll("\\\\", "/");
        File f = new File(filePath);
        if(!f.exists()) {
            return null;
        }

        Map<String, Object> result = Maps.newHashMap();

        String ct = GenerateIdUtil.getStrId();
        String targetPath = Constant.DEFAULT_CARD_TEMP_DIR + ct + (f.getName().substring(f.getName().lastIndexOf(".")));
        FileUtil.copyAndRename(f.getAbsolutePath(), targetPath); // 拷贝文件并且重命名

        // 创建临时目录， 存放过程图片
        String tempPath =  Constant.DEFAULT_CARD_TEMP_DIR + ct + "/";
        FileUtil.createDir(tempPath);

        Boolean debug = true;
        Mat src = ImageUtil.imread(targetPath, CvType.CV_8UC3);

        new IdCardUtil(); // 调用构造方法，加载模型文件
        // 执行识别
        Mat card = IdCardUtil.cardDetect(src, debug, tempPath);
        if(card.cols() == 0 || card.rows() == 0){ // 未识别到
            result.put("idNum", "识别失败");
        } else {
            ImageUtil.debugImg(debug, tempPath, "src", card);
            String idNum = IdCardUtil.txtDetect(card, debug, tempPath);

            Vector<String> debugFiles = new Vector<String>(); // 查询debug文件
            FileUtil.getFiles(tempPath, debugFiles);
            result.put("debugFiles", debugFiles);
            result.put("idNum", idNum);
        }

        new File(targetPath).delete();  // 删除拷贝的临时文件
        card.release();
        src.release();
        return result;
    }



}
